import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";


Vue.use(VueRouter)

const routes = [
    //主页
    {


        path: '/',
        component: () => import('../views/Manage.vue'),
        redirect: '/CreateView',
        children: [
            {path: 'home', name: '首页', component: () => import('../views/Home.vue')},
            {
                path: 'homeview',
                name: '用户页面',
                component: () => import('@/views/home/HomeView.vue'),
                meta: {title:'用户信息管理',requiresAuth: true, requiresLevel2: true}
            },
            {path: '/person', name: 'Person', component: () => import('@/views/Person.vue')},
            {
                path: 'admin/contestinfo',
                name: '比赛信息页面',
                component: () => import('../views/admin/ContestInfo.vue'),
                meta: {title:'比赛信息页面',requiresAuth: true, requiresLevel2: true}
            },
            {path: '/CreateView', name: '创建队伍', component: () => import('@/views/CreateView.vue')},
            {
                path: '/StatisticsAndManagement',
                name: '统计和管理',
                component: () => import('@/views/admin/StatisticsAndManagement.vue'),
                meta: {title:'统计和管理', requiresAuth: true, requiresLevel2: true}
            },
            {path: '/AwardInfo', name: '获奖管理', component: () => import('@/views/admin/AwardInfo')},

        ],
        meta: {

            requiresAuth: true
        }
    },
    //登录
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/Login.vue'),
        meta: { title: '登录' }
    },
    //注册
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/register/Register.vue')
    },

]
//这里采用分离式，routes对应的是上面的代码，只是分开了
const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})


router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('user');
    const userLevel = localStorage.getItem('level');

    // 根据路由中的 meta 设置页面标题
    if (to.meta && to.meta.title) {
        document.title = to.meta.title;
    } else {
        document.title = '学科竞赛管理系统'; // 设置默认标题
    }

    if (to.matched.some(record => record.meta.requiresAuth) && !token) {
        // 需要登录权限的页面，用户未登录，跳转到登录页
        next({path: '/login'});
    } else if (to.matched.some(record => record.meta.requiresLevel2) && userLevel !== "1") {
        next({path: '/CreateView'});
    } else {
        localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称，为了在Header组件中去使用
        store.commit("setPath")  // 触发store的数据更新
        next();
    }
});

export default router
